﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using ConfigLibrary;
using HtmlAgilityPack;
using MySql.Data;
using MySql.Data.MySqlClient;


namespace wmdata
{
    public partial class wmdata : mysqlconn
    {      
        
        public wmdata(string wmdatabases)
        {
            wmdatabse = wmdatabases;
            this.Load += new EventHandler(wmdata_Load);            
            emailpassword();
        }

        public void emailpassword()
        {
            Stream s = File.Open(Properties.Settings.Default.CONFIGTEST, FileMode.Open);
            BinaryFormatter b = new BinaryFormatter();
            Config config = (Config)b.Deserialize(s);
            s.Close();
            config.GetQbInfo(out _qbusername, out _qbpass);
        }

        public void wmdata_Load(object sender, EventArgs e)
        {
            wmweb.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(wmweb_DocumentCompleted);
            wmweb.AllowNavigation = true;
            switch (wmdatabse)
            {
                case "spock":
                    wmweb.Navigate("https://wmt.quickbase.com/db/bez7ue92u?a=q&qid=1004420&qrppg=1000", false);
                    break;
                case "trident":
                    wmweb.Navigate("https://wmt.quickbase.com/db/bfngn7tvg?a=q&qid=1003041&qrppg=1000", false);
                    break;
            }
            
        }

        void wmweb_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            
            DataRow[] row;
            int rowid = 0;            

            if (loggin == false)
            {
                try
                {
                    HtmlElement email = wmweb.Document.GetElementById("loginid");
                    email.SetAttribute("value", _qbusername);
                    connect(mysqlconnection);
                    mysqlconnection.Open();
                    loadtables("p");
                    p = ds.Tables["p"];                   
                    row = p.Select("date = max(date)");
                    rowid = (int)row[0]["idp"];
                    dt = (DateTime)row[0]["date"];
                    HtmlElement password = wmweb.Document.GetElementById("password");
                    password.SetAttribute("value", row[0]["pass"].ToString());                    
                    HtmlElement signin = wmweb.Document.GetElementById("signin");
                    signin.InvokeMember("click");
                    loggin = true;
                }
                catch (Exception ex)
                {
                    string subject = "1st attempt at login";
                    ErrorHandling.ErrorEmail(subject, ex);
                }
            }
            else if (loggin == true)
            {
                try
                {
                    DateTime today = DateTime.Today;
                    dt = dt.AddDays(58);
                    if (today == dt)
                    {
                        passwordpage = new password(p);
                        passwordpage.ShowDialog();
                    }         


                    HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
                    doc.Load(wmweb.DocumentStream);
                    HtmlNodeCollection rows = null;
                    HtmlNodeCollection cells = null;
                    switch (wmdatabse)
                    {
                        case "spock":
                            rows = doc.DocumentNode.SelectNodes("//table[@id='VR_bez7ue92u_1004420']//tr");
                            cells = doc.DocumentNode.SelectNodes("//table[@id='VR_bez7ue92u_1004420']//tr//td");
                            break;
                        case "trident":
                            rows = doc.DocumentNode.SelectNodes("//table[@id='VR_bfngn7tvg_1003041']//tr");
                            cells = doc.DocumentNode.SelectNodes("//table[@id='VR_bfngn7tvg_1003041']//tr//td");
                            for (int i = 2; i < rows.Count; i++)
                            {
                                string record = rows[i].ChildNodes[3].InnerText.ToString();
                                tridentpage = new trident(record, wmdatabse);
                                tridentpage.ShowDialog();
                            }
                            break;

                    }

                    //header(cells);
                    tablebody(rows);
                }       
                
                catch (Exception ex)
                {

                }
            }
        }

        //private void header(HtmlNodeCollection cells)
        //{
        //    try
        //    {
        //        string headercell = cells[1].InnerText.ToString();
        //        headercell = headercell.Replace("\r\n", " ").Trim();
        //        CheckHeaderExist(headercell);
        //        string th = wmdataset.Tables["wmdata"].Columns["record_id"].ToString();
        //        if (headercell != th) throw new Exception();
        //    }
        //    catch (Exception ex)
        //    {
        //        string subject = "header error";
        //        ErrorHandling.ErrorEmail(subject, ex);
        //    }
        //}

        private void tablebody(HtmlNodeCollection rows)
        {
            
        }

        DateTime dt = new DateTime();
        string[] datatables;
        public static DataTable p;
        public static trident tridentpage;
        public static password passwordpage;
        public string wmdatabse;
        public static wmdata newpage;
        WebBrowser wmweb = new WebBrowser();
        MySqlConnection mysqlconnection = new MySqlConnection();
        private static string _qbusername;
        private static string _qbpass;
        bool loggin = false;
    }
}
